package web.servlet;

import commons.Constatns;
import exception.UserNotFoundException;
import pojo.User;
import service.Impl.UserLoginServiceImpl;
import service.UserLoginService;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login.do")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String userpwd = req.getParameter("userpwd");
        String code = req.getParameter("code");
        try {

            HttpSession session = req.getSession();
            String code1 =(String) session.getAttribute("code");
            if(code.equals(code1)){
                UserLoginService userLoginService=new UserLoginServiceImpl();
                User userlogin = userLoginService.userlogin(username, userpwd);
                String userid =String.valueOf(userlogin.getUserid());


                String id = session.getId();
                session.setAttribute(Constatns.User_Session_key,userlogin);

                ServletContext servletContext = this.getServletContext();
//            HttpSession attribute = (HttpSession) servletContext.getAttribute(userlogin.getUserid() + "");
//            if(attribute != null){
//                attribute.removeAttribute(userlogin.getUserid()+"");
//                attribute.invalidate();
//            }
//            servletContext.setAttribute(userlogin.getUserid()+"",session);

                String attribute =(String) servletContext.getAttribute(userid);
                if(attribute!= null && !attribute.equals(id)){
                    try {

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                servletContext.setAttribute(userid,id);
                session.setAttribute(Constatns.User_Session_key,userlogin);
                resp.sendRedirect("main.jsp");
            }else {
                req.setAttribute(Constatns.VALIDATE_CODE_KEY,"验证码有误,请重新输入");
                req.getRequestDispatcher("login.do").forward(req,resp);
            }

        }catch (UserNotFoundException e){
            req.setAttribute(Constatns.Login_Msg,e.getMessage());
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }catch (Exception e){
            resp.sendRedirect("error.jsp");
        }
    }
}
